import React, { useEffect, useRef, useState } from "react";
import { Button } from "antd-mobile";
import * as echarts from "echarts/core";
import {
  TooltipComponent,
  BrushComponent,
  LegendComponent,
  DataZoomComponent,
  GridComponent,
  ToolboxComponent,
  MarkLineComponent,
  MarkPointComponent,
} from "echarts/components";
import { CandlestickChart, LineChart, BarChart } from "echarts/charts";
import { SVGRenderer, CanvasRenderer } from "echarts/renderers";
import { Toast } from "antd-mobile";
import { type KlineDataItem } from "@api/stock";
import styles from "@styles/components/stock/kline-chart.module.css";

// 注册必需的组件
echarts.use([
  TooltipComponent,
  BrushComponent,
  LegendComponent,
  DataZoomComponent,
  GridComponent,
  ToolboxComponent,
  MarkLineComponent,
  MarkPointComponent,
  CandlestickChart,
  LineChart,
  BarChart,
  SVGRenderer,
  CanvasRenderer,
]);

export interface KlineChartProps {
  data: KlineDataItem[];
  loading?: boolean;
}

// 计算移动平均线函数
const calculateMA = (data: number[], count: number) => {
  const result: (number | null)[] = [];
  for (let i = 0; i < data.length; i++) {
    if (i < count - 1) {
      result.push(null);
    } else {
      const sum = data.slice(i - count + 1, i + 1).reduce((a, b) => a + b, 0);
      result.push(sum / count);
    }
  }
  return result;
};

const KlineChart: React.FC<KlineChartProps> = ({ data, loading = false }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [showMA, setShowMA] = useState(true); // 默认显示移动平均线
  const [showIndicators, setShowIndicators] = useState(true); // 显示技术指标（布林带、标记点等）
  const [tooltipInfo, setTooltipInfo] = useState<{
    visible: boolean;
    data?: {
      date: string;
      item: KlineDataItem;
    };
  }>({ visible: false });

  // 初始化图表
  useEffect(() => {
    if (!chartRef.current) return;

    const timer = setTimeout(() => {
      if (!chartRef.current) return;

      if (chartInstance.current) {
        chartInstance.current.dispose();
      }

      const containerWidth = chartRef.current.offsetWidth; // 使用容器的实际宽度
      const containerHeight = 500; // 调整图表高度与CSS容器高度匹配

      try {
        chartInstance.current = echarts.init(
          chartRef.current,
          "light",
          {
            renderer: "svg", // 使用SVG渲染器
            width: containerWidth,
            height: containerHeight,
          }
        );
        console.log("图表初始化成功");
      } catch (error) {
        console.error("图表初始化失败:", error);
        Toast.show("图表初始化失败");
      }
    }, 100);

    return () => {
      clearTimeout(timer);
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, []);

  // 渲染图表数据
  useEffect(() => {
    if (!chartInstance.current) return;

    // 保存引用以便在清理函数中使用
    const chartDom = chartRef.current;
    
    let currentTouchHandler: ((e: TouchEvent) => void) | null = null;

    // 使用父组件传递的真实数据
    const chartData = data;

    // 如果没有数据则直接返回，不显示图表
    if (!chartData || chartData.length === 0) return;

    try {
      // 清理之前的事件监听器
      chartInstance.current.off("click");
      if (chartInstance.current.getZr) {
        chartInstance.current.getZr().off("click");
      }

      // 准备数据
      const dates = chartData.map((item) => {
        const date = new Date(item.time_key);
        return date.getMonth() + 1 + "/" + date.getDate();
      });

      const klineData = chartData.map((item) => [
        Number(item.open),
        Number(item.close),
        Number(item.low),
        Number(item.high),
      ]);

      const volumeData = chartData.map((item) => Number(item.volume));
      const closeData = chartData.map((item) => Number(item.close));

      // 计算移动平均线数据
      const ma5Data = calculateMA(closeData, 5);
      const ma20Data = calculateMA(closeData, 20);
      const ma250Data = calculateMA(closeData, 250);

      // 计算最高点和最低点
      const highestPoint = Math.max(...closeData);
      const lowestPoint = Math.min(...closeData);

      // 计算布林带
      const calculateBollinger = (data: number[], period: number = 20) => {
        const result: {
          upper: (number | null)[];
          middle: (number | null)[];
          lower: (number | null)[];
        } = {
          upper: [],
          middle: [],
          lower: [],
        };

        for (let i = 0; i < data.length; i++) {
          if (i < period - 1) {
            result.upper.push(null);
            result.middle.push(null);
            result.lower.push(null);
          } else {
            const slice = data.slice(i - period + 1, i + 1);
            const mean = slice.reduce((a, b) => a + b, 0) / period;
            const variance =
              slice.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / period;
            const stdDev = Math.sqrt(variance);

            result.middle.push(mean);
            result.upper.push(mean + 2 * stdDev);
            result.lower.push(mean - 2 * stdDev);
          }
        }
        return result;
      };

      const bollinger = calculateBollinger(closeData);

      // 合并图表配置
      const option = {
        backgroundColor: "transparent",
        animation: false,
        legend: {
          show: false, // 不显示图例，我们自定义MA显示
        },
        grid: [
          {
            left: "3%", // 减少左边距，让Y轴标签更靠近左边
            right: "3%",
            top: "8%",
            height: "60%", // 增加K线图高度
            containLabel: true, // 确保标签不会被裁剪
          },
          {
            left: "3%", // 减少左边距，让Y轴标签更靠近左边
            right: "3%",
            top: "70%",
            height: "25%", // 增加成交量图高度
            containLabel: true, // 确保标签不会被裁剪
          },
        ],
        xAxis: [
          {
            type: "category",
            data: dates,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            axisLabel: {
              show: true, // K线图显示x轴标签（日期）
              fontSize: 10,
              color: "#666",
              interval: "auto", // 自动间隔，让ECharts根据可视区域智能显示
              margin: 8,
            },
            axisTick: {
              show: true,
              interval: "auto", // 自动间隔显示刻度
            },
            gridIndex: 0,
          },
          {
            type: "category",
            data: dates,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            axisLabel: {
              show: false, // 成交量图不显示x轴标签
              fontSize: 9,
            },
            axisTick: {
              show: false,
              interval: 0,
            },
            gridIndex: 1,
          },
        ],
        yAxis: [
          {
            scale: true,
            position: "left", // 明确设置Y轴在左侧
            splitArea: { show: true },
            axisLabel: {
              fontSize: 10,
              color: "#666",
              margin: 5, // 减少标签与轴线的距离
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#ddd",
              },
            },
            axisTick: {
              show: true,
              length: 3,
            },
            gridIndex: 0,
          },
          {
            scale: true,
            position: "left", // 明确设置Y轴在左侧
            splitNumber: 3,
            axisLabel: {
              show: false, // 隐藏成交量的Y轴标签
              fontSize: 9,
              color: "#666",
              margin: 5, // 减少标签与轴线的距离
              formatter: (value: number) => {
                if (value >= 10000) {
                  return (value / 10000).toFixed(0) + "万";
                }
                return value.toString();
              },
            },
            axisLine: {
              show: false, // 隐藏成交量的Y轴线
              lineStyle: {
                color: "#ddd",
              },
            },
            axisTick: {
              show: false, // 隐藏成交量的Y轴刻度
              length: 3,
            },
            splitLine: { show: false },
            gridIndex: 1,
          },
        ],
        dataZoom: [
          {
            type: "inside",
            xAxisIndex: [0, 1],
            start: 30, // 调整起始位置，显示最近的数据。
            end: 100,
            zoomOnMouseWheel: true, // 表示不按任何功能键，鼠标移动能触发数据窗口平移。
            moveOnMouseMove: true, // 表示不按任何功能键，鼠标滚轮能触发数据窗口平移。
            moveOnMouseWheel: false, // 表示鼠标滚轮不能触发平移。避免与页面垂直滚动冲突
            preventDefaultMouseMove: false, // 是否阻止 mousemove 事件的默认行为。
            // 移动端触摸优化
            zoomLock: false, // 允许缩放
            throttle: 100, // 节流，提高性能
            // 启用触摸拖拽
            disabled: false, // 确保dataZoom启用
            orient: "horizontal", // 水平拖拽
            filterMode: 'none', // 不过滤数据点，保持平滑
          },
        ],
        tooltip: { 
          show: true, // 启用tooltip来显示十字线
          trigger: 'axis',
          backgroundColor: 'transparent', // 透明背景
          borderWidth: 0,
          formatter: () => '', // 不显示tooltip内容，只显示十字线
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999',
              width: 1,
              type: 'dashed',
              opacity: 0.8,
            },
            label: {
              show: true,
              backgroundColor: '#fff',
              borderColor: '#999',
              textStyle: {
                color: '#333',
                fontSize: 10,
              },
            },
          },
        },
        series: [
          {
            name: "K线",
            type: "candlestick",
            data: klineData,
            xAxisIndex: 0,
            yAxisIndex: 0,
            itemStyle: {
              color: "#00a86e", // 港股上涨绿色实心
              color0: "transparent", // 港股下跌红色空心
              borderColor: "#00a86e", // 上涨边框绿色
              borderColor0: "#f03955", // 下跌边框红色
              borderWidth: 1,
            },
            emphasis: {
              itemStyle: {
                color: "#00a86e",
                color0: "transparent",
                borderColor: "#00a86e",
                borderColor0: "#f03955",
                borderWidth: 2,
              },
            },
            // 添加最高点和最低点标记
            ...(showIndicators
              ? {
                  markPoint: {
                    data: [
                      {
                        name: "最高点",
                        type: "max",
                        valueDim: "highest",
                        symbol: "circle", // 恢复为小圆点作为锚点
                        symbolSize: 8, // 小圆点
                        itemStyle: {
                          color: "#f03955",
                          borderWidth: 0,
                        },
                        label: {
                          show: true,
                          formatter: "{c}",
                          position: "top", // 文本位置在上方
                          color: "#f03955", // 红色文本
                          fontSize: 11,
                          backgroundColor: "rgba(255, 255, 255, 0.8)", // 半透明白色背景增强可读性
                          borderRadius: 3,
                          padding: [2, 4], // 内边距
                        },
                      },
                      {
                        name: "最低点",
                        type: "min",
                        valueDim: "lowest",
                        symbol: "circle", // 恢复为小圆点作为锚点
                        symbolSize: 8, // 小圆点
                        itemStyle: {
                          color: "#00a86e",
                          borderWidth: 0,
                        },
                        label: {
                          show: true,
                          formatter: "{c}",
                          position: "bottom", // 文本位置在下方
                          color: "#00a86e", // 绿色文本
                          fontSize: 11,
                          borderRadius: 3,
                          backgroundColor: "rgba(255, 255, 255, 0.8)", // 半透明白色背景增强可读性
                          padding: [2, 4], // 内边距
                        },
                      },
                    ],
                  },
                  // 添加重要价位线
                  markLine: {
                    silent: true,
                    symbol: ["none", "none"],
                    data: [
                      {
                        name: "平均价格",
                        type: "average",
                        valueDim: "close",
                        lineStyle: {
                          color: "#999",
                          type: "dashed",
                          width: 1,
                          opacity: 0.6,
                        },
                        label: {
                          show: true,
                          formatter: "均价: {c}",
                          position: "insideEndTop",
                          color: "#999",
                          fontSize: 10,
                        },
                      },
                      // 支撑线（最低点水平线）
                      {
                        name: "支撑位",
                        yAxis: lowestPoint,
                        lineStyle: {
                          color: "#00a86e",
                          type: "solid",
                          width: 1,
                          opacity: 0.7,
                        },
                        label: {
                          show: true,
                          formatter: "支撑: {c}",
                          position: "insideEndBottom",
                          color: "#00a86e",
                          fontSize: 10,
                        },
                      },
                      // 阻力线（最高点水平线）
                      {
                        name: "阻力位",
                        yAxis: highestPoint,
                        lineStyle: {
                          color: "#f03955",
                          type: "solid",
                          width: 1,
                          opacity: 0.7,
                        },
                        label: {
                          show: true,
                          formatter: "阻力: {c}",
                          position: "insideEndTop",
                          color: "#f03955",
                          fontSize: 10,
                        },
                      },
                    ],
                  },
                }
              : {}),
          },
          // 移动平均线系列
          ...(showMA
            ? [
                {
                  name: "MA5",
                  type: "line",
                  data: ma5Data,
                  smooth: true,
                  lineStyle: { opacity: 0.8, width: 1, color: "#fbbf24" },
                  showSymbol: false,
                  xAxisIndex: 0,
                  yAxisIndex: 0,
                },
                {
                  name: "MA20",
                  type: "line",
                  data: ma20Data,
                  smooth: true,
                  lineStyle: { opacity: 0.8, width: 1, color: "#8b5cf6" },
                  showSymbol: false,
                  xAxisIndex: 0,
                  yAxisIndex: 0,
                },
                {
                  name: "MA250",
                  type: "line",
                  data: ma250Data,
                  smooth: true,
                  lineStyle: { opacity: 0.8, width: 1, color: "#06b6d4" },
                  showSymbol: false,
                  xAxisIndex: 0,
                  yAxisIndex: 0,
                },
                // 布林带上轨
                {
                  name: "布林上轨",
                  type: "line",
                  data: bollinger.upper,
                  smooth: true,
                  lineStyle: {
                    opacity: 0.6,
                    width: 1,
                    color: "#ff6b9d",
                    type: "dashed",
                  },
                  showSymbol: false,
                  xAxisIndex: 0,
                  yAxisIndex: 0,
                },
                // 布林中轨
                {
                  name: "布林中轨",
                  type: "line",
                  data: bollinger.middle,
                  smooth: true,
                  lineStyle: {
                    opacity: 0.6,
                    width: 1,
                    color: "#9ca3af",
                    type: "solid",
                  },
                  showSymbol: false,
                  xAxisIndex: 0,
                  yAxisIndex: 0,
                },
                // 布林下轨
                {
                  name: "布林下轨",
                  type: "line",
                  data: bollinger.lower,
                  smooth: true,
                  lineStyle: {
                    opacity: 0.6,
                    width: 1,
                    color: "#10b981",
                    type: "dashed",
                  },
                  showSymbol: false,
                  xAxisIndex: 0,
                  yAxisIndex: 0,
                },
              ]
            : []),
          // 成交量系列
          {
            name: "成交量",
            type: "bar",
            data: volumeData,
            xAxisIndex: 1,
            yAxisIndex: 1,
            itemStyle: {
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              color: function (params: any) {
                const dataIndex = params.dataIndex;
                const current = chartData[dataIndex];
                if (current.change_rate >= 0) {
                  return "#00a86e"; // 港股上涨绿色实心
                } else {
                  return "transparent"; // 港股下跌红色空心
                }
              },
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              borderColor: function (params: any) {
                const dataIndex = params.dataIndex;
                const current = chartData[dataIndex];
                return current.change_rate >= 0 ? "#00a86e" : "#f03955";
              },
              borderWidth: 1,
              opacity: 0.7,
            },
            // 成交量标记点
            markPoint: {
              data: [
                {
                  name: "最大成交量",
                  type: "max",
                  symbol: "circle",
                  symbolSize: 8,
                  itemStyle: {
                    color: "#ff9500",
                  },
                  label: {
                    show: true,
                    formatter: "量最大\n{c|0}万",
                    position: "top",
                    color: "#ff9500",
                    fontSize: 9,
                    borderRadius: 3,
                    backgroundColor: "rgba(255, 255, 255, 0.8)", // 半透明白色背景增强可读性
                    rich: {
                      c: {
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        formatter: (params: any) => (params / 10000).toFixed(0),
                      },
                    },
                  },
                },
              ],
            },
            // 成交量平均线
            markLine: {
              data: [
                {
                  name: "成交量均线",
                  type: "average",
                  lineStyle: {
                    color: "#ff9500",
                    type: "dashed",
                    width: 1,
                    opacity: 0.6,
                  },
                  label: {
                    show: true,
                    formatter: "均量",
                    position: "insideEndTop",
                    color: "#ff9500",
                    fontSize: 9,
                  },
                },
              ],
            },
          },
          // 成交量移动平均线
          ...(showMA
            ? [
                {
                  name: "量MA5",
                  type: "line",
                  data: calculateMA(volumeData, 5),
                  smooth: true,
                  lineStyle: {
                    opacity: 0.7,
                    width: 1,
                    color: "#fbbf24",
                  },
                  showSymbol: false,
                  xAxisIndex: 1,
                  yAxisIndex: 1,
                },
                {
                  name: "量MA10",
                  type: "line",
                  data: calculateMA(volumeData, 10),
                  smooth: true,
                  lineStyle: {
                    opacity: 0.7,
                    width: 1,
                    color: "#8b5cf6",
                  },
                  showSymbol: false,
                  xAxisIndex: 1,
                  yAxisIndex: 1,
                },
              ]
            : []),
        ],
      };

      // 设置图表配置
      chartInstance.current.setOption(option, true);

      // 移动端触摸优化 - 改进处理逻辑，区分水平拖拽和垂直滚动
      if (chartDom) {
        let startX = 0;
        let startY = 0;
        let isDragging = false;
        let isVerticalScroll = false;

        const touchHandler = (e: TouchEvent) => {
          if (e.touches.length > 1) {
            return; // 允许多指缩放页面
          }
          
          const rect = chartDom.getBoundingClientRect();
          const touch = e.touches[0];
          const isInChart = touch.clientX >= rect.left && 
                           touch.clientX <= rect.right && 
                           touch.clientY >= rect.top && 
                           touch.clientY <= rect.bottom;
          console.log("touch", touch);
          console.log("isInChart", isInChart);
          
          if (!isInChart) return;

          switch (e.type) {
            case 'touchstart': {
              startX = touch.clientX;
              startY = touch.clientY;
              isDragging = false;
              isVerticalScroll = false;
              break;
            }
              
            case 'touchmove': {
              const deltaX = Math.abs(touch.clientX - startX);
              const deltaY = Math.abs(touch.clientY - startY);
              
              // 如果还没有确定拖拽方向
              if (!isDragging && !isVerticalScroll) {
                // 移动距离超过阈值才判断方向
                if (deltaX > 10 || deltaY > 10) {
                  // 水平移动距离大于垂直移动距离，认为是水平拖拽
                  if (deltaX > deltaY * 1.5) {
                    isDragging = true;
                    e.preventDefault(); // 阻止页面滚动，让图表处理水平拖拽
                  } else {
                    // 垂直移动距离更大，认为是垂直滚动
                    isVerticalScroll = true;
                    // 不阻止默认行为，允许页面垂直滚动
                  }
                }
              } else if (isDragging) {
                // 已确定为水平拖拽，继续阻止默认行为
                e.preventDefault();
              }
              // 如果是垂直滚动，不做任何处理，让页面自然滚动
              break;
            }
          }
        };
        
        currentTouchHandler = touchHandler;
        
        chartDom.addEventListener('touchstart', touchHandler, { passive: false });
        chartDom.addEventListener('touchmove', touchHandler, { passive: false });
      }

      // K线图点击事件处理 - 使用ZRender事件而不是ECharts事件
      chartInstance.current.off("click");

      // 添加触摸事件支持（移动端）
      const zr = chartInstance.current.getZr();
      zr.off("click");
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      zr.on("click", (event: any) => {
        console.log("ZRender点击事件:", event); // 调试日志
        console.log("点击目标:", event.target); // 调试目标对象
        console.log("点击位置:", { x: event.offsetX, y: event.offsetY });

        // 获取点击位置相对于图表的坐标
        const pointInGrid = [event.offsetX, event.offsetY];

        try {
          // 将像素坐标转换为数据索引
          const dataIndex = chartInstance.current!.convertFromPixel(
            { gridIndex: 0 },
            pointInGrid
          );
          console.log("转换的数据索引:", dataIndex);

          if (
            dataIndex &&
            typeof dataIndex[0] === "number" &&
            dataIndex[0] >= 0 &&
            dataIndex[0] < chartData.length
          ) {
            const index = Math.round(dataIndex[0]);
            const item = chartData[index];

            console.log("找到数据项:", item);

            // 显示tooltip数据
            setTooltipInfo({
              visible: true,
              data: {
                date: dates[index],
                item: item,
              },
            });

            // 显示十字线到指定位置
            chartInstance.current!.dispatchAction({
              type: 'showTip',
              seriesIndex: 0,
              dataIndex: index,
            });

            console.log("Tooltip和十字线已显示");
            return; // 找到数据了，不要隐藏tooltip
          }
        } catch (error) {
          console.error("坐标转换错误:", error);
        }

        // 如果没有找到有效数据或点击的是空白区域，隐藏tooltip和十字线
        console.log("点击了空白区域或无效区域，隐藏tooltip和十字线");
        setTooltipInfo({ visible: false });
        
        // 隐藏十字线
        chartInstance.current!.dispatchAction({
          type: 'hideTip',
        });
      });
    } catch (error) {
      console.error("图表渲染错误:", error);
      Toast.show("图表渲染失败");
    }

    // 清理函数
    return () => {
      // 清理图表事件
      if (chartInstance.current) {
        chartInstance.current.off("click");
        const zr = chartInstance.current.getZr();
        if (zr) {
          zr.off("click");
        }
      }
      
      // 清理触摸事件
      if (chartDom && currentTouchHandler) {
        chartDom.removeEventListener('touchstart', currentTouchHandler);
        chartDom.removeEventListener('touchmove', currentTouchHandler);
      }
    };
  }, [data,  showMA, showIndicators]);

  // 计算最新MA值用于显示
  const closeData = data.map((item) => Number(item.close));

  const ma5Data = calculateMA(closeData, 5);
  const ma20Data = calculateMA(closeData, 20);
  const ma250Data = calculateMA(closeData, 250);

  const latestMA5 = ma5Data[ma5Data.length - 1];
  const latestMA20 = ma20Data[ma20Data.length - 1];
  const latestMA250 = ma250Data[ma250Data.length - 1];

  return (
    <div className={styles.klineChartContainer}>
      {/* 控制栏 */}
      <div className={styles.klineChartControls}>
        <div className={styles.chartTitle}>
          <span>日K线图</span>
        </div>
      </div>

      {/* 固定位置的tooltip - 显示在MA区域上方 */}
      <div className={styles.fixedTooltip}>
        <div className={styles.tooltipRow}>
          <span>日期: {tooltipInfo.data?.date || "--"}</span>
          <span>
            开盘:{" "}
            {tooltipInfo.data?.item
              ? Number(tooltipInfo.data.item.open).toFixed(2)
              : "--"}
          </span>
          <span>
            收盘:{" "}
            {tooltipInfo.data?.item
              ? Number(tooltipInfo.data.item.close).toFixed(2)
              : "--"}
          </span>
        </div>
        <div className={styles.tooltipRow}>
          <span>
            最高:{" "}
            {tooltipInfo.data?.item
              ? Number(tooltipInfo.data.item.high).toFixed(2)
              : "--"}
          </span>
          <span>
            最低:{" "}
            {tooltipInfo.data?.item
              ? Number(tooltipInfo.data.item.low).toFixed(2)
              : "--"}
          </span>
          <span>
            成交量:{" "}
            {tooltipInfo.data?.item
              ? (Number(tooltipInfo.data.item.volume) / 10000).toFixed(1) + "万"
              : "--"}
          </span>
        </div>
        <div className={styles.tooltipRow}>
          <span>
            涨跌幅:
            {tooltipInfo.data?.item ? (
              <span
                style={{
                  color:
                    tooltipInfo.data.item.change_rate >= 0
                      ? "#00a86e"
                      : "#f03955",
                  marginLeft: "4px",
                }}
              >
                {tooltipInfo.data.item.change_rate >= 0 ? "+" : ""}
                {Number(tooltipInfo.data.item.change_rate).toFixed(2)}%
              </span>
            ) : (
              "--"
            )}
          </span>
        </div>
      </div>

      {/* 图表容器 - 支持横向滚动 */}
      <div className={styles.klineChartWrapper}>
        {/* MA显示区域 - 独立于图表 */}
        {showMA && data.length > 0 && (
          <div className={styles.maDisplay}>
            <span className={`${styles.maItem} ${styles.ma5}`}>
              MA5: {latestMA5 ? latestMA5.toFixed(2) : "--"}
            </span>
            <span className="ma-item ma20">
              MA20: {latestMA20 ? latestMA20.toFixed(2) : "--"}
            </span>
            <span className="ma-item ma250">
              MA250: {latestMA250 ? latestMA250.toFixed(2) : "--"}
            </span>
          </div>
        )}

        {/* K线图和成交量合并容器 */}
        <div className={styles.chartSection}>
          <div
            ref={chartRef}
            className={styles.klineChart}
            style={{
              width: "100%",
              height: "500px", // 调整图表高度与CSS保持一致
              opacity: loading ? 0.5 : 1,
              transition: "opacity 0.3s",
              // 优化移动端触摸，允许图表内部处理拖拽
              touchAction: 'pan-x', // 只允许水平拖拽，垂直方向交给页面处理
            }}
          />
        </div>
      </div>

      {/* MA控制按钮区域 */}
      <div className={styles.maControls}>
        <Button
          fill="none"
          size="small"
          onClick={() => setShowMA(!showMA)}
          style={{
            color: showMA
              ? "#1677ff"
              : "#999",
            marginRight: "8px",
          }}
        >
          MA
        </Button>
        <Button
          fill="none"
          size="small"
          onClick={() => setShowIndicators(!showIndicators)}
          style={{
            color: showIndicators
              ? "#1677ff"
              : "#999",
          }}
        >
          指标
        </Button>
      </div>

      {loading && <div className={styles.loadingMask}>正在加载K线数据...</div>}

      {/* 无数据提示 */}
      {!loading && (!data || data.length === 0) && (
        <div className={styles.loadingMask}>暂无K线数据</div>
      )}
    </div>
  );
};

export default KlineChart;
